<?php
/**
 * Created by PhpStorm.
 * User: Season
 * Date: 2018/10/23
 * Time: 14:00
 */

namespace app\api\service;


use app\lib\enum\ScopEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    public static function generateToken(){
        //32字符组成随机字符串
        $randChars = getRandChars(32);
        //时间戳
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //特殊加密
        $salt = config ('secure.token_salt');
        return md5 ($randChars.$timestamp.$salt);
    }

    public static function getCurrentTokenVar($key){
        $token = Request::instance () -> header ('token');
        $vars = Cache::get ($token);
        if(!$vars){
            throw new TokenException();
        }
        else{
            if(!is_array ($vars)){
                $vars = json_decode ($vars,true);
            }
            if(array_key_exists ($key, $vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的Token变量并不存在');
            }
        }
    }

    public static function getCurrentUID(){
        //token
        $uid = self::getCurrentTokenVar ('uid');
        return $uid;
    }

    //用户和管理员都需要
    public static function needPrimaryScope(){
        $scope = self::getCurrentTokenVar ('scope');
        if($scope){
            if ($scope >= ScopEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }
    }

    public static function needExclusiveScope(){
        $scope = self::getCurrentTokenVar ('scope');
        if($scope){
            if ($scope == ScopEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }
    }

    public static function isValidOperate($checkedUID){
        if(!$checkedUID){
            throw new Exception('检测UID时必须传入一个被检测的UID');
        }
        $currentOperateUID = self::getCurrentUID ();
        if($currentOperateUID == $checkedUID){
            return true;
        }
        return false;
    }

    public static function verifyToken($token){
        $exist = Cache::get ($token);
        if($exist){
            return true;
        }else{
            return false;
        }
    }
}